import { defineStore } from 'pinia'
import { ref } from 'vue'
import { store } from '@/stores'
import checkRoutes from '@/router/checkRoutes'
import noCheckRoutes from '@/router/noCheckRoutes'

/**
 * 检查用户是否有权限访问该路由
 * @param roles 用户角色集合
 * @param route 路由
 * @returns {boolean}
 */
const hasPermission = (roles, route) => {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 递归过滤有权限的异步(动态)路由
 * @param routes 接口返回的异步(动态)路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes, roles) => {
  const res = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

// setup
export const usePermissionStore = defineStore('permission', () => {
  // state
  const routes = ref([])
  const isLoading = ref(false)

  // actions
  function setRoutes(newRoutes) {
    routes.value = noCheckRoutes.concat(newRoutes)
  }

  /**
   * 生成动态路由
   * @param roles 用户角色集合
   * @returns {Promise<unknown>}
   */
  function generateRoutes(roles) {
    return new Promise((resolve) => {
      let accessedRoutes
      if (roles.includes('all') || roles.includes('admin')) {
        accessedRoutes = checkRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(checkRoutes, roles)
      }
      isLoading.value = true
      resolve(accessedRoutes)
    })
  }

  return { routes, setRoutes, generateRoutes, isLoading }
})

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
